//
//  ShareViewController.swift
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/24.
//

import UIKit
import Photos
import SVProgressHUD

enum ShareType {
    case normal
    case activityAnalyze(rows: Int = 0)
    case diary
}

protocol ShareViewControllerDelegate: class {
    func shareWeChatDone(img: UIImage)
    func shareWeiboDone(img: UIImage)
}

class ShareViewController: UIViewController {
    
    @IBOutlet weak var codeImgV: UIImageView!
    @IBOutlet weak var imgV: UIImageView!
    @IBOutlet weak var functionView: UIView!
    @IBOutlet weak var shareImgV: UIImageView!
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var weChatView: UIView!
    @IBOutlet weak var weiboView: UIView!
    @IBOutlet weak var downloadView: UIView!
    
    @IBOutlet weak var bgViewHeight: NSLayoutConstraint!
    
    weak var delegate: ShareViewControllerDelegate?
    
    var type: ShareType?
    
    var img: UIImage?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
//        let btn = UIButton()
//        btn.backgroundColor = .orange
//        btn.frame = CGRect(x: 20.0, y: 20.0, width: 100.0, height: 100.0)
//        shareImgV.addSubview(btn)
        
        
        switch type {
        case .normal: break
        case .activityAnalyze(let rows):
            if rows == 0 {
                bgViewHeight.constant = CGFloat(screen_height - Double(functionView.height) - safeBottom_height - 60.0)
            } else {
                bgViewHeight.constant = 420.0 + CGFloat((rows - 1)) * 60.0
            }
            
        case .diary:
            bgViewHeight.constant = CGFloat(screen_height - Double(functionView.height) - safeBottom_height - 60.0)
        default: break
        }
        
//        bgView.image = UIImage(named: "分享背景") ?? UIImage()
        
        imgV.image = img
        
        functionView.layer.cornerRadius = 12.0
        
        let tap0 = UITapGestureRecognizer(target: self, action: #selector(wechatShareAction))
        weChatView.addGestureRecognizer(tap0)
        let tap1 = UITapGestureRecognizer(target: self, action: #selector(weiboShareAction))
        weiboView.addGestureRecognizer(tap1)
        let tap2 = UITapGestureRecognizer(target: self, action: #selector(downloadAction))
        downloadView.addGestureRecognizer(tap2)
        
    }
    
    // 友盟页面统计
    override func viewWillAppear(_ animated: Bool)
    {
        super.viewWillAppear(animated)
        MobClick.beginLogPageView("分享")
        MobClick.event("pages_num", attributes: ["FenXiang":"进入分享"])
    }
    
    override func viewWillDisappear(_ animated: Bool)
    {
        super.viewWillDisappear(animated)
        MobClick.endLogPageView("分享")
        MobClick.event("pages_num", attributes: ["FenXiang":"离开分享"])
    }
}

extension ShareViewController {
    
    @IBAction func cancelAction(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
    
    @objc func wechatShareAction() {
        dismiss(animated: true, completion: nil)
        delegate?.shareWeChatDone(img: bgView.captureImage ?? UIImage())
        
        // 友盟功能统计
        MobClick.event("function_num", attributes: ["WeiXinFenXiang":"微信分享"])
    }
    
    @objc func weiboShareAction() {
        dismiss(animated: true, completion: nil)
        delegate?.shareWeiboDone(img: bgView.captureImage ?? UIImage())
        // 友盟功能统计
        MobClick.event("function_num", attributes: ["WeiBoFenXiang":"微博分享"])
    }
    
    @objc func downloadAction() {
        
//        guard var bgImg = UIImage(named: "分享背景") else { return }
//        bgImg = bgImg.stretchableImage(withLeftCapWidth: 2, topCapHeight: 0)
//        bgImg = bgImg.scaleImg(to: bgView.size)
//        
//        var path = FileImg.getImagePath(bgImg)
//        guard var img = UIImage(contentsOfFile: path) else { return }
//        img = QRCodeTool.share().create(withBgImage: img, contentImage: imgV.image ?? UIImage())
//        path = FileImg.getImagePath(img)
//        guard let img2 = UIImage(contentsOfFile: path) else { return }
        
        // 友盟功能统计
        MobClick.event("function_num", attributes: ["BaoCunDaoShouJi":"保存到手机"])
        
        let img2 = bgView.captureImage ?? UIImage()
        PHPhotoLibrary.shared().performChanges({
            PHAssetChangeRequest.creationRequestForAsset(from: img2)
        }) { (isSuccess: Bool, error: Error?) in
            DispatchQueue.main.async {
                if isSuccess {
                    SVProgressHUD.showSuccess(withStatus: "保存成功")
                    SVProgressHUD.dismiss(withDelay: 2.0)
                } else{
                    SVProgressHUD.showError(withStatus: "保存失败")
                    SVProgressHUD.dismiss(withDelay: 2.0)
                }
            }
        }
    }
        
    func addImage(img: UIImage, bgImg: UIImage) -> UIImage? {
        UIGraphicsBeginImageContext(CGSize(width: bgImg.size.width, height: bgImg.size.height))
        bgImg.draw(in: CGRect(x: 0, y: 0, width: bgImg.size.width, height: bgImg.size.height))
        img.draw(in: CGRect(x: 10.0, y: 10.0, width: bgImg.size.width - 10.0 * 2, height: bgImg.size.height - 10.0 * 2))
        guard let resultImg = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
        UIGraphicsEndImageContext()
        return resultImg
    }
    
}
